<template>
  <div class="comment-container">
    <header class="header">
      <h1>评论区</h1>
    </header>
    <main class="main">
      <section class="main-left">
        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="textarea"> </el-input>
      </section>
      <section class="main-right">
        <el-button type="success" @click="send">发送<i class="el-icon-s-promotion el-icon--right"></i></el-button>
      </section>
    </main>
    <footer class="footer">
      <el-card class="box-card" v-for="(item, index) in comments" :key="index" shadow="hover">
        <div class="item-left">
          <el-avatar shape="square" :size="50" src="https://www.ipicbed.com/images/2021/12/23/avater02.th.jpg"></el-avatar>
          <h1>{{ item.username }}</h1>
        </div>
        <div class="item-right">
          <div class="text item">
            {{ item.content }}
          </div>
          <div class="item-footer">评论时间：{{ item.comment_time }}</div>
        </div>
      </el-card>
    </footer>

  </div>
</template>

<script>
export default {
  name: 'Comment',
  props: ['id', 'commentArea'],
  data () {
    return {
      textarea: '',
      comments: this.commentArea
    }
  },
  methods: {
    async send () {
      const username = localStorage.getItem('username')
      if (username) {
        // 复杂数据类型（数组对象结合）需要json序列化后才能发送给服务器解析（反序列化）
        const commentItems = {
          username,
          role: localStorage.getItem('role'),
          user_id: localStorage.getItem('_id'),
          comment_time: new Date(),
          content: this.textarea
        }
        const formData = {
          _id: this.id,
          commentItems: JSON.stringify(commentItems)
        }
        const { data: res } = await this.$api.editComment(formData)
        this.comments = res.data.commentArea
        this.textarea = ''
        console.log(res)
      } else {
        this.$notify({
          title: '警告',
          message: '登录后，才能评论。',
          type: 'warning'
        })
        setTimeout(() => {
          this.$router.replace('/')
        }, 1000)
      }
    }
  },
  watch: {
    commentArea (newVal, oldVal) {
      this.comments = newVal
    }
  }
}
</script>

<style lang="less" scoped>
.header {
  font-size: 20px;
  margin-bottom: 15px;
}
.main {
  display: flex;
  margin-bottom: 15px;
}
.main-left {
  flex: 9;
}
.main-right {
  flex: 1;
}
/deep/ .el-button--success {
  height: 100%;
}
// .footer{

// }
.text {
  font-size: 14px;
}

.box-card {
  width: 100%;
  margin-bottom: 15px;
}
/deep/ .el-card__body {
  display: flex;
  padding: 15px;
}
.item {
  padding: 0 0;
}
.item-left {
  flex: 1;
}
.item-left h1 {
  padding-left: 10px;
}
.item-right {
  position: relative;
  flex: 6;
}
.item-footer {
  // margin-top: 10px;
  position: absolute;
  bottom: 0;
  left: 0;
}
</style>
